// user_announcement.js

import express from 'express';
const router = express.Router();
import { createConnectionPool } from '../../mysql/index.js';

// Define a route to handle the PUT request
router.put('/announcement/update', async (req, res) => {
    console.log(`reqreq`, req.query);
    const { id, announcement_text } = req.query;

    // 验证是否提供了 announcement_text 和 id
    if (!id || !announcement_text) {
        return res.status(400).json({ error: 'id 和 announcement_text 都是必需的' });
    }

    try {
        const pool = await createConnectionPool();
        // 检查是否存在给定 ID 的记录
        const checkQuery = 'SELECT * FROM user_announcement WHERE id = ?';
        const [checkResult] = await pool.query(checkQuery, [id]);

        if (checkResult.length === 0) {
            // 如果不存在，执行插入操作
            const insertQuery = 'INSERT INTO user_announcement (id, announcement_text, created_at) VALUES (?, ?, CURRENT_TIMESTAMP)';
            const [insertResult] = await pool.query(insertQuery, [id, announcement_text]);
            console.log('Insert Query:', insertQuery);

            // 检查插入是否成功
            if (insertResult.affectedRows > 0) {
                res.status(200).json({ message: '插入成功' });

            } else {
                res.status(400).json({ error: '插入操作失败' });
            }
        } else {
            // 如果存在，执行更新操作

            const updateQuery = 'UPDATE user_announcement SET announcement_text = ?, created_at = CURRENT_TIMESTAMP WHERE id = ?';
            const [updateResult] = await pool.query(updateQuery, [announcement_text, id]);


            // 检查更新是否成功
            if (updateResult.affectedRows > 0) {
                res.status(200).json({ message: '更新成功' });
            } else {
                res.status(400).json({ error: '更新操作失败' });
            }
        }
    } catch (error) {
        console.error('更新/插入 user_announcement 记录时出错:', error);
        res.status(500).json({ error: '内部服务器错误', details: error.message });
    }
});


router.get('/announcement/get', async (req, res) => {
    const { id } = req.query;
    if (!id) {
        res.status(400).json({ error: 'id 都是必需的' });
        return
    }
    const pool = await createConnectionPool();
    try {
        const query = `SELECT * FROM user_announcement WHERE id = ${Number(id)}`;
        const result = await pool.query(query);
        res.status(200).send({ code: 200, msg: '获取数据成功', data: result[0] })
    } catch (error) {
        console.error('Error executing query:', error);
        res.status(500).json({ error: 'Internal Server Error' });
    } finally {
        // 释放连接池资源
        await pool.end();
    }
})




export default router;
